package jdbcDemo;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class JdbcDemo1 {

    public static void main(String[] args) {
        // 用户名
        String userName = "root";

        // 密码
        String passWord = "123456";

        // 用户连接地址 8.x
        String url = "jdbc:mysql://106.12.33.28/java_bighomework?useSSL=true&useUnicode=true&characterEncoding=UTF8&serverTimezone=UTC";

        // 数据库连接驱动 8.x
        String driver = "com.mysql.cj.jdbc.Driver";


        Connection conn = null;

        try {

            JdbcUtil jdbcUtil = new JdbcUtil();
            conn = jdbcUtil.getConnection();
            if (conn!=null){
                System.out.println("连接成功");
            }else{
                System.out.println("连接失败");
            }

            String sql = "";
            List<String> params = new ArrayList<String>();

            opa(sql,params,jdbcUtil);
            opb(sql,params,jdbcUtil);


            conn.close();

        } catch (Exception e) {
            e.printStackTrace();
        }


    }
    private static void opb(String sql,List<String> params,JdbcUtil jdbcUtil) throws Exception {
        sql = "SELECT id, user_id, user_name, user_ip FROM users WHERE id = ?";
        params = Arrays.asList(new String[]{"1"});
        List<Map<String, Object>> mapList = jdbcUtil.findResult(sql, params);

        for (Map<String, Object> value:mapList){
            System.out.println(value);
        }

    }

    private static void opa(String sql,List<String> params,JdbcUtil jdbcUtil) throws SQLException {
        System.out.println("--------------添加测试");
        sql = "INSERT INTO users (user_id,user_pwd,user_name,user_ip,user_port) values(?, ?, ?, ?, ?)";
        params = Arrays.asList(new String[]{"002", "123456", "andy2", "127.0.0.1", "12345"});
        boolean insterFlag = jdbcUtil.updateByPreparedStatement(sql, params);
        if (insterFlag){
            System.out.println("插入成功");
        }else {
            System.out.println("插入失败");
        }


        System.out.println("--------------修改测试");
        sql = "UPDATE users SET user_name = ?,user_ip = ? WHERE id = ?";
        params = Arrays.asList(new String[]{"李白", "192,168.1.1","1"});
        boolean updateflag = jdbcUtil.updateByPreparedStatement(sql, params);
        if (updateflag){
            System.out.println("修改成功");
        }else {
            System.out.println("修改失败");
        }


        System.out.println("--------------删除测试");
        sql = "DELETE FROM users WHERE id = ?";
        params = Arrays.asList(new String[]{"3"});
        boolean deleteFLAG = jdbcUtil.updateByPreparedStatement(sql, params);
        if (deleteFLAG){
            System.out.println("删除成功");
        }else {
            System.out.println("删除失败");
        }
    }
}
